// SPDX-FileCopyrightText: 2023-2025 Sangfor Technologies Inc.
// SPDX-License-Identifier: Mulan PSL v2
package com.geniusai.aip.auth.domain.convertor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author hml14563
 * @date 2021/4/15
 */
@Slf4j
public class BaseConverter<DO, VO> {
    /**
     * 批量对象转换
     */
    public List<VO> convertList(List<DO> fromList, Class<VO> clazz) {
        Optional<List<DO>> doOpt = Optional.ofNullable(fromList);
        return doOpt
                .map(dos -> dos.stream().map(d -> convert(d, clazz)).collect(Collectors.toList()))
                .orElse(null);
    }

    /**
     * 单个对象转换
     */
    public VO convert(DO from, Class<VO> clazz) {
        if (from == null) {
            return null;
        }
        VO to = null;
        try {
            to = clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            log.error("初始化{}对象失败。", clazz, e.getMessage());
        }
        convert(from, to);
        return to;
    }

    /**
     * 属性拷贝方法，有特殊需求时子类覆写此方法
     */
    protected void convert(DO from, VO to) {
        BeanUtils.copyProperties(from, to);
    }
}
